<template>
  <div>
    <el-dialog v-model="dialogFormVisible" title="编辑动态">
      <el-form :model="form">
        <el-form-item label="标题" label-width="140px">
          <el-input v-model="form.title" autocomplete="off" />
        </el-form-item>

        <el-form-item label="内容" label-width="140px">
          <el-input v-model="form.content" autocomplete="off" type="textarea" />
        </el-form-item>

        <el-form-item label="图片" label-width="140px">
          <el-upload
            v-model:file-list="form.img"
            action="/api/upload/img"
            :headers="tokenBody"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="hanleSuccess"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="Edit"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog title="发布动态" v-model="ShopDialogFormVisible">
      <el-form :model="insert">
        <el-form-item label="动态标题" label-width="140px">
          <el-input v-model="insert.title" placeholder="请输入动态标题" />
        </el-form-item>

        <el-form-item label="动态内容" label-width="140px">
          <el-input
            v-model="insert.content"
            placeholder="请输入动态内容"
            type="textarea"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="ShopDialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="insertAll"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>

    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/manager/index' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/manager/find">动态信息</a></el-breadcrumb-item>
    </el-breadcrumb>
    <div class="header" />
    <div class="insert">
      <el-button type="info" size="large" @click="ChooseIF" style="margin-right: 50px"
        >发布动态</el-button
      >
    </div>

    <el-table :data="tableData" style="width: 100%">
      <el-table-column label="动态标题" prop="title" width="200px" />
      <el-table-column label="动态内容" width="400px">
        <template #default="scope">
          <div v-text="scope.row.content"></div>
        </template>
      </el-table-column>

      <el-table-column label="发布者" prop="userId"></el-table-column>
      <el-table-column label="发布时间" prop="inputTime" width="200px"></el-table-column>
      <el-table-column
        label="更新日志时间"
        prop="updateTime"
        width="200px"
      ></el-table-column>

      <el-table-column label="Operations" width="200px">
        <template #default="scope">
          <div v-show="scope.row.state == 1">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >移除</el-button
            >
          </div>
          <div v-show="scope.row.state != 1">已移除</div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pageSize"
      v-model:page-size="pageItem"
      :page-sizes="[20, 30, 50, 100]"
      :small="small"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="ItemTotal"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script lang="ts" setup>
import axios from "axios";
import { ref, reactive } from "vue";
import { Timer, Message } from "@element-plus/icons-vue";
import { el } from "element-plus/es/locale";
import { ElMessage, ElMessageBox } from "element-plus";
import { Delete, Download, Plus, ZoomIn } from "@element-plus/icons-vue";
import type { UploadFile } from "element-plus";
import type { UploadProps, UploadUserFile } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";

const token = ref(localStorage.getItem("admin_token"));
const tokenBody = ref({
  token: token.value,
});
const optionList = ref([
  {
    label: "正常",
    value: "1",
  },
  {
    label: "关闭",
    value: "0",
  },
]);
const ShopDialogFormVisible = ref(false);

const Edit = () => {
  const req = {
    findId: form.findId,
    content: form.content,
    title: form.title,
    img: form.realImg,
  };
  axios
    .post("/api/manager/find/update", req, {
      headers: {
        token: token.value,
      },
    })
    .then((res) => {
      // console.log(res);
      if (res.data.success) {
        ElMessage({
          message: "更新成功",
          type: "success",
        });
      } else {
        ElMessage({
          message: res.data.message,
          type: "error",
        });
      }
      search();
    })
    .catch((err) => {
      console.log(err);
    });

  setTimeout(() => {
    dialogFormVisible.value = false;
  }, 200);
};
const small = ref(false);
const background = ref(false);
const disabled = ref(false);
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  search();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  search();
};

// const fileList = ref<UploadUserFile[]>([]);

const dialogFormVisible = ref(false);
const photoShowFlag = ref(false);
const dialogImageUrl = ref("");

const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  // console.log(uploadFile, uploadFiles);
};

const hanleSuccess: UploadProps["onSuccess"] = (res) => {
  // console.log(res);
  // form.img.push({
  //   name: res.message,
  //   url: res.message,
  // });
  // console.log(form.img);
  // console.log(form.img.length);
  // console.log(JSON.stringify(form.realImg));
  // console.log(JSON.stringify(form.img));
  const arr = [];

  form.img.forEach((el) => {
    if (el.percentage) {
      arr.push(el.response.message);
    } else {
      arr.push(el.url);
    }
  });
  form.realImg = JSON.stringify(arr);
  // console.log("form.realImg :", form.realImg);
};

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  photoShowFlag.value = true;
};

interface log {
  findId: number;
  inputTime: Date;
  updateTime: Date;
  state: number;
  userId: string;
  img: string;
  content: string;
  title: string;
}

const insert = reactive({
  title: "",
  content: "",
  img: [], //源上传的img
  realImg: "", //真实json数据的img
});

const insertAll = () => {
  const req = {
    title: insert.title,
    content: insert.content,
    img: insert.realImg,
  };
  axios
    .post("/api/find/insert", req, {
      headers: {
        token: token.value,
      },
    })
    .then((res) => {
      console.log(res);
      if (res.data.success) {
        ElMessage({
          type: "success",
          message: "新建成功",
        });
      } else {
        ElMessage({
          type: "error",
          message: res.data.message,
        });
      }
    })
    .catch((err) => {
      console.log(err);
    });
  setTimeout(() => {
    insert.title = "";
    insert.content = "";
    insert.img = [];
    insert.realImg = "";
    ShopDialogFormVisible.value = false;
    search();
  }, 200);
};
/**
 * 用于表格的数据展示
 * */
const form = reactive({
  findId: 0,
  inputTime: new Date(),
  updateTime: new Date(),
  state: 1,
  content: "",
  title: "",
  img: <UploadUserFile[]>[], //源文件上传img
  realImg: "", //真实json的图像
});

const handleEdit = (index: number, row: log) => {
  form.findId = row.findId;
  form.inputTime = new Date();
  form.updateTime = new Date();
  form.state = 1;
  form.content = "";
  form.title = "";
  form.img = <UploadUserFile[]>[];
  form.realImg = "";
  axios
    .get("/api/manager/find/get/" + row.findId, {
      headers: {
        token: token.value,
      },
    })
    .then((res) => {
      console.log(res);
      const msg = res.data.message;
      form.findId = msg.findId;
      form.inputTime = msg.inputTime;
      form.updateTime = msg.updateTime;
      form.state = msg.state;
      form.content = msg.content;
      form.title = msg.title;
      if (msg.img) {
        msg.img = JSON.parse(msg.img);
        form.realImg = msg.img;
        msg.img.forEach((el) => {
          form.img.push({
            name: el,
            url: el,
          });
        });
        console.log("form.img :", form.img);
      }
    })
    .catch((err) => {
      console.log(err);
    });

  setTimeout(() => {
    dialogFormVisible.value = true;
    console.log(index, row);
  }, 300);
};
const handleDelete = (index: number, row: log) => {
  console.log(index, row);
  console.log(row);

  ElMessageBox.confirm("是否删除这条动态" + row.title, "警告", {
    confirmButtonText: "确认删除",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      axios
        .get("/api/manager/find/del/" + row.findId, {
          headers: {
            token: token.value,
          },
        })
        .then((res) => {
          console.log(res);
          if (res.data.success) {
            ElMessage({
              type: "success",
              message: "删除成功",
            });
          } else {
            ElMessage({
              type: "error",
              message: res.data.message,
            });
          }
          search();
        })
        .catch((err) => {
          console.log(err);
        });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

const tableData = ref([]);
const input = ref("");
const pageSize = ref(1);
const pageItem = ref(20);
const PageTotal = ref(0);
const ItemTotal = ref(0);

const reactSearch = () => {
  pageSize.value = 1;
  pageItem.value = 20;
  setTimeout(() => {
    search();
  }, 200);
};

const search = () => {
  axios
    .get(
      "/api/manager/find/select/" +
        pageSize.value +
        "/" +
        pageItem.value +
        "?name=" +
        input.value,
      {
        headers: {
          token: token.value,
        },
      }
    )
    .then((res) => {
      console.log(res);
      const msg = res.data.message.list;
      console.log(msg);
      tableData.value = msg;
      console.log(tableData.value);
      PageTotal.value = res.data.message.pages;
      ItemTotal.value = res.data.message.total;
    })
    .catch((err) => {
      console.log(err);
    });
};
const ChooseIF = () => {
  ShopDialogFormVisible.value = true;
};

search();
</script>

<style lang="scss" scoped>
.header {
  height: 50px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.insert {
  display: flex;
  justify-content: flex-end;
  width: 100%;
}
.demo-image__error .image-slot {
  font-size: 30px;
}
.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}
.demo-image__error .el-image {
  width: 100%;
  height: 200px;
}
</style>
